package com.valsong.sandbox.mock.logger;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import com.valsong.sandbox.mock.LoggerAdjustment;
import org.slf4j.ILoggerFactory;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Optional;

import static com.valsong.sandbox.mock.constant.MockConstants.LOG_LEVEL;

public class LogbackAdjustment implements LoggerAdjustment {

    @Override
    public void setLogLevel(Map<String, String> param) {
        String logLevel = Optional.ofNullable(param)
                .map(p -> p.get(LOG_LEVEL))
                .orElse(null);

        ILoggerFactory iLoggerFactory = LoggerFactory.getILoggerFactory();
        if (logLevel != null && !logLevel.trim().isEmpty() && iLoggerFactory instanceof LoggerContext) {
            LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
            loggerContext.getLogger(Logger.ROOT_LOGGER_NAME).setLevel(Level.toLevel(logLevel, Level.INFO));
        }

    }
}
